#include "socket.hpp"
#include <thread>
#include <mutex>
#include "HttpProtocol.hpp"
//http底层协议是tcp
class httpServer{
    
    std::mutex _muetx;

    public:
    using func_t = std::function<std::string(std::string&)> ; 
    httpServer(uint16_t port,func_t task)
    :_port(port)
    ,_listensocket(new Net_TcpSocket::TcpSocket,[](Net_TcpSocket::TcpSocket* &ptr){delete ptr; ptr = nullptr;})
    ,_hander_task(task)
    {
        _listensocket->BuildListenSocket(port,Net_TcpSocket::default_backlog);
    }
    ~httpServer()
    {

    }
    
    void WorkLoop()
    {
        while(1)
        {            
            std::lock_guard lk(_muetx);    
            std::string peerip;   
            uint16_t peerport;
            std::shared_ptr<Net_TcpSocket:: Socket> newsock ( _listensocket->AcceptConnection(&peerip,&peerport));
            if(!newsock) continue;
            std::cout<<"获取了新连接:Client Ip"<<peerip<<", peer Port"<<peerport<<"\n";
            
            std::thread td(_HanderRequest,newsock,_hander_task);
            td.detach();
        }
    }
    private:
    int _port;
    std::shared_ptr<Net_TcpSocket::Socket> _listensocket;
    func_t _hander_task;
    static std::function<void(std::shared_ptr<Net_TcpSocket:: Socket>,func_t hander_task)> _HanderRequest;
};


std::function<void(std::shared_ptr<Net_TcpSocket:: Socket>,httpServer:: func_t hander_task)> httpServer:: _HanderRequest= [](std::shared_ptr<Net_TcpSocket:: Socket> sockptr,httpServer:: func_t hander_task){
    std::string inbufferstream;
    sockptr->Recv(&inbufferstream,4096*8);//这里不一定读取到合理的报文，是可能出现问题的
    sockptr->Send(hander_task(inbufferstream));
    sockptr->CloseSocket();
};